import React, { useState, useEffect, useRef } from "react";
import { StyleSheet, View, Text } from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useTheme } from "@/hooks/useTheme";

interface TimerProps {
  duration: number; // in seconds
  onComplete?: () => void;
  size?: "small" | "medium" | "large";
  showIcon?: boolean;
}

export default function Timer({
  duration,
  onComplete,
  size = "medium",
  showIcon = true,
}: TimerProps) {
  const { colors } = useTheme();
  const [timeLeft, setTimeLeft] = useState(duration);
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  useEffect(() => {
    timerRef.current = setInterval(() => {
      setTimeLeft((prevTime) => {
        if (prevTime <= 1) {
          if (timerRef.current) clearInterval(timerRef.current);
          if (onComplete) onComplete();
          return 0;
        }
        return prevTime - 1;
      });
    }, 1000);
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [onComplete]);
  const formatTime = (seconds: number) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes.toString().padStart(2, "0")}:${remainingSeconds
      .toString()
      .padStart(2, "0")}`;
  };
  const getWarningColor = () => {
    const percentage = timeLeft / duration;
    if (percentage <= 0.25) return colors.error;
    if (percentage <= 0.5) return colors.warning;
    return colors.text;
  };
  const getFontSize = () => {
    switch (size) {
      case "small":
        return 14;
      case "large":
        return 24;
      default:
        return 18;
    }
  };
  const getIconSize = () => {
    switch (size) {
      case "small":
        return 14;
      case "large":
        return 24;
      default:
        return 18;
    }
  };
  return (
    <View style={styles.container}>
      {showIcon && (
        <Ionicons
          name="time-outline"
          size={getIconSize()}
          color={getWarningColor()}
          style={styles.icon}
        />
      )}
      <Text
        style={[
          styles.time,
          {
            color: getWarningColor(),
            fontSize: getFontSize(),
          },
        ]}
      >
        {formatTime(timeLeft)}
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: "row",
    alignItems: "center",
  },
  icon: {
    marginRight: 6,
  },
  time: {
    fontWeight: "600",
  },
});
